<?php

namespace App\Http\Controllers\WF\Systems;

use DB;
use Carbon\Carbon;
use App\Http\Controllers\WF\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\Wf\WfMenu;
use App\Eloqumd\Wf\WfCompany;
use App\Eloqumd\Wf\WfRole;
use App\Eloqumd\Wf\WfUser;
use App\Eloqumd\Wf\WfDictAccess;
use App\Eloqumd\Wf\WfDictType;

class AuthorizeController extends ApiController
{
    public function getAuthorizeTree(Request $request)
    {
        $type = $request->input('type', 'com');

        $jsonData = [];

        $menuWhere = null;
        $menuWhere[] = ['status', '=', 1, 'AND'];
        $menuWhere[] = ['show', '=', 1, 'AND'];

        switch ($type) {
            // 单位
            case 'com':
                $companyId = $request->input('companyId', 0);
                $menuData = WfMenu::where($menuWhere)
                    ->orderBy('order_num', 'asc')
                    ->orderBy('id', 'asc')
                    ->get()
                    ->toArray();
                $auth = WfCompany::where('id', $companyId)->value('auth');
                $checked = $auth == '' ? [] : explode(',', $auth);
                $trees = $this->getAuthList($companyId, $menuData, 0);
                break;
            // 字典
            case 'dict':
                $companyId = $request->input('companyId', 0);
                $auths = null;
                $dictAuths = WfDictAccess::where('company_id', $companyId)->value('dicts');
                if ($dictAuths) {
                    $auths = explode(',', $dictAuths);
                }
                $checked = is_null($auths) ? [] : $auths;
                $dictData = WfDictType::select([
                    'id', 'name as label'
                ])->orderBy('id', 'asc')->get()->toArray();

                $trees = $dictData;
                break;
            // 用户
            case 'user':
                $userId = $request->input('userId', 0);
                $whereIn = [];
                if ($this->apiUser['user_type'] == 0) {
                    $menuWhere = null;
                } else {
                    $companyAuths = WfCompany::where('id', $this->apiUser['company_id'])->value('auth');
                    $whereIn = ['id', explode(',', $companyAuths)];
                }
                $query = WfMenu::where($menuWhere);
                if ($whereIn) {
                    $query->whereIn($whereIn[0], $whereIn[1]);
                }
                $query->orderBy('order_num', 'asc')->orderBy('id', 'asc');
                $menuData = $query->get()->toArray();

                $checked = explode(',', WfUser::where('id', $userId)->value('auth'));
                $trees = $this->getAuthList($this->apiUser['company_id'], $menuData, 0);
                break;
            // // 用户数据权限
            // case 'userjuris':
            //     $userID = $this->request->param('userID/d', 0);
            //     $companyID = $this->saasUser['company_id'];
            //     $tempTrees = Company::get($companyID)->toArray();
            //     $tempTrees['id'] = $companyID;
            //     $tempTrees['label'] = $tempTrees['company_name'];
            //     $tempTrees['children'] = Common::getOrgTree($companyID);
            //     $trees = [$tempTrees];
            //     $checked = explode(',', User::where('id', $userID)->value('dataauth'));
            //     break;
            // 角色
            case 'role':
                $roleId = $request->input('roleId', 0);
                $whereIn = [];
                if ($this->apiUser['user_type'] == 0) {
                    $menuWhere = null;
                } else {
                    $companyAuths = WfCompany::where('id', $this->apiUser['company_id'])->value('auth');
                    $whereIn = ['id', explode(',', $companyAuths)];
                }

                $query = WfMenu::where($menuWhere);
                if ($whereIn) {
                    $query->whereIn($whereIn[0], $whereIn[1]);
                }
                $query->orderBy('order_num', 'asc')->orderBy('id', 'asc');
                $menuData = $query->get()->toArray();

                $checked = explode(',', WfRole::where('id', $roleId)->value('auth'));
                $trees = $this->getAuthList($this->apiUser['company_id'], $menuData, 0);
                break;
            default:
                $trees = [];
                $checked = [];
                break;
        }

        $jsonData['tree'] = $trees;
        $jsonData['checked'] = $checked;

        return $this->jsonReturns(10000, $this->success, $jsonData);
    }

    private function getAuthList($comapnyID, $data, $pid)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $pid) {
                $v['data'] = $this->getAuthList($comapnyID, $data, $v['id']);
                $tree[] = [
                    'id' => $v['id'],
                    'label' => $v['title'],
                    'children' => $v['data'],
                ];
            }
        }

        return $tree;
    }

    public function authorizeCompany(Request $request)
    {
        $companyId = $request->input('companyId');
        $auths = $request->input('auths', '');
        $auths = empty($auths) ? '' : (
            is_array($auths) && count($auths) ? implode(",", $auths) : rtrim($auths, ',')
        );

        DB::beginTransaction();
        try {
            $model = WfCompany::find($companyId);
            $model->auth = $auths;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function authorizeRole(Request $request)
    {
        $roleId = $request->input('roleId');
        $auths = $request->input('auths', '');
        $auths = empty($auths) ? '' : (
            is_array($auths) && count($auths) ? implode(",", $auths) : rtrim($auths, ',')
        );

        DB::beginTransaction();
        try {
            $model = WfRole::find($roleId);
            $model->auth = $auths;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function authorizeUser(Request $request)
    {
        $userId = $request->input('userId');
        $auths = $request->input('auths', '');
        $auths = empty($auths) ? '' : (
            is_array($auths) && count($auths) ? implode(",", $auths) : rtrim($auths, ',')
        );

        DB::beginTransaction();
        try {
            $model = WfUser::find($userId);
            $model->auth = $auths;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    public function authorizeDict(Request $request)
    {
        $companyId = $request->input('companyId');
        $auths = $request->input('auths', '');
        $auths = empty($auths) ? '' : (
            is_array($auths) && count($auths) ? implode(",", $auths) : rtrim($auths, ',')
        );

        DB::beginTransaction();
        try {
            $hasRecord = (array)WfDictAccess::where('company_id', $companyId)->first();
            if (empty($hasRecord)) {
                $model = new WfDictAccess;
                $model->created_at = Carbon::now();
                $model->company_id = $companyId;
            } else {
                $model = WfDictAccess::find($hasRecord['id']);
                $model->updated_at = Carbon::now();
            }
            
            $model->dicts = $auths;
            $model->save();
        
            DB::commit();
        
            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
        
    }
}
